#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

struct event {
    char comm[128];
};

static int handle_event(void *ctx, void *data, size_t data_sz)
{
    struct event *e = data;
    printf("comm: %s\n", e->comm);
    return 0;
}

int main()
{
    struct bpf_object *obj;
    struct bpf_program *prog;
    struct ring_buffer *rb;
    struct bpf_map *map;
    int map_fd;

    obj = bpf_object__open_file("kern.o", NULL);
    if (!obj) {
        perror("Failed to open BPF object file");
        return -1;
    }

    if (bpf_object__load(obj)) {
        perror("Failed to load BPF object");
        return -1;
    }

    prog = bpf_object__find_program_by_name(obj, "bpf_prog");
    if (!prog) {
        fprintf(stderr, "Failed to find BPF program\n");
        return -1;
    }

    map = bpf_object__find_map_by_name(obj, "ringbuf");
    if (!map) {
        fprintf(stderr, "Failed to find ringbuf map\n");
        return -1;
    }

    if (!bpf_program__attach(prog)) {
        perror("Failed to attach BPF program");
        return -1;
    }

    printf("Successfully attached BPF program. Reading ringbug...\n");

    rb = ring_buffer__new(bpf_map__fd(map), handle_event, NULL, NULL);
    if (!rb) {
        fprintf(stderr, "Failed new ringbuf\n");
        return -1;
    }

    while (true) {
        if (ring_buffer__poll(rb, 100) < 0)
            break;
    }

    return 0;
}
